package com.smag.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smag.common.constant.SystemConstants;
import com.smag.common.core.domain.AjaxResult;
import com.smag.common.core.domain.entity.FarmOrder;
import com.smag.common.core.domain.entity.FarmProduct;
import com.smag.common.exception.base.BaseException;
import com.smag.common.utils.SecurityUtils;
import com.smag.common.utils.bean.BeanUtils;
import com.smag.common.utils.uuid.IdUtils;
import com.smag.system.domain.FarmOrderAddress;
import com.smag.system.domain.FarmOrderProduct;
import com.smag.system.domain.dto.AddProductOrderDto;
import com.smag.system.domain.vo.OrderVo;
import com.smag.system.mapper.FarmOrderMapper;
import com.smag.system.service.*;
import com.smag.system.mapper.FarmOrderProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author hzqhzq
 * @description 针对表【farm_order_product】的数据库操作Service实现
 * @createDate 2023-04-26 10:35:15
 */
@Service
public class FarmOrderProductServiceImpl extends ServiceImpl<FarmOrderProductMapper, FarmOrderProduct>
        implements FarmOrderProductService {
    @Resource
    private FarmProductService farmProductService;
    @Resource
    private FarmCartService farmCartService;
    @Autowired
    private FarmOrderService farmOrderService;
    @Autowired
    private FarmOrderAddressService farmOrderAddressService;
    @Autowired
    private FarmOrderMapper farmOrderMapper;

    @Transactional
    @Override
    public AjaxResult addProductOrder(Long userId, AddProductOrderDto addProductOrderDto) {
        Long orderId = IdUtils.numberUUID();
        AtomicReference<Integer> price = new AtomicReference<>(0);
        List<FarmOrderProduct> farmOrderProducts = addProductOrderDto.getProducts().stream().map(farmProduct -> {
            FarmOrderProduct farmOrderProduct = new FarmOrderProduct();
            farmOrderProduct.setUserId(userId);
            farmOrderProduct.setProductId(farmProduct.getId());
            farmOrderProduct.setAmount(farmProduct.getAmount());
            farmOrderProduct.setAddressId(addProductOrderDto.getAddressId());
            farmOrderProduct.setOrderId(orderId);
            farmOrderProduct.setProductPrice(farmProduct.getPrice());
            FarmProduct farmProduct2 = farmProductService.selectFarmProductById(farmOrderProduct.getProductId());
            farmCartService.deleteShoppingCart(userId, farmProduct.getId());
            if (farmProduct2.getAmount() - farmProduct.getAmount() < 0) {
                throw new BaseException("商品数量不足");
            }
            farmProduct2.setAmount(farmProduct2.getAmount() - farmProduct.getAmount());
            farmProduct2.setSales(farmProduct2.getSales() + farmProduct.getAmount());
            farmProductService.updateFarmProduct(farmProduct2);
            price.set(Integer.parseInt(farmProduct.getAmount().toString()) * Integer.parseInt(farmProduct.getPrice().toString())+price.get());
            return farmOrderProduct;
        }).collect(Collectors.toList());
        FarmOrder farmOrder = new FarmOrder();
        FarmOrderAddress farmOrderAddress = farmOrderAddressService.getById(addProductOrderDto.getAddressId());
        farmOrder.setName(farmOrderAddress.getName());
        farmOrder.setOrderId(orderId);
        farmOrder.setStatus("0");
        farmOrder.setPhonenumber(farmOrderAddress.getPhone());
        farmOrder.setAddress(farmOrderAddress.getAddress());
        farmOrder.setPrice(BigDecimal.valueOf(price.get()));
        farmOrder.setCreateBy(SecurityUtils.getUserId());
        farmOrderService.insertFarmOrder(farmOrder);
        if (saveBatch(farmOrderProducts)) {
            return AjaxResult.success("结算成功");
        }
        return AjaxResult.error("结算失败");
    }

    @Override
    public AjaxResult listOrders(Long userId) {
        List<Long> orderIds = getBaseMapper().getOrderId(userId);
        List<List<OrderVo>> orderVos = orderIds.stream().map(orderId -> {
            LambdaQueryWrapper<FarmOrderProduct> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FarmOrderProduct::getOrderId, orderId);
            return list(wrapper).stream().map(farmOrderProduct -> {
                FarmProduct farmProduct = farmProductService.selectFarmProductById(farmOrderProduct.getProductId());
                OrderVo orderVo = BeanUtils.copyBean(farmOrderProduct, OrderVo.class);
                orderVo.setProductPrice(farmProduct.getPrice());
                orderVo.setAvatar(farmProduct.getAvatar());
                orderVo.setProductName(farmProduct.getName());
                return orderVo;
            }).collect(Collectors.toList());
        }).collect(Collectors.toList());
        return AjaxResult.success(orderVos);
    }

    @Override
    public AjaxResult payOrder(Long orderId) {

        if (getBaseMapper().payOrder(orderId, SystemConstants.ORDER_STATUS_PAY,new Date()) > 0) {
            FarmOrder order = farmOrderMapper.getByOrderId(orderId);
            order.setStatus(String.valueOf(SystemConstants.ORDER_STATUS_PAY));
            farmOrderMapper.updateByOrderId(order);
            return AjaxResult.success("付款成功");
        }
        return AjaxResult.error("付款失败");
    }
}




